package com.dj.product.k2faas.jpa.config;

import net.ttddyy.dsproxy.listener.logging.SLF4JLogLevel;
import net.ttddyy.dsproxy.support.ProxyDataSource;
import net.ttddyy.dsproxy.support.ProxyDataSourceBuilder;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.ReflectionUtils;

import javax.sql.DataSource;
import java.lang.reflect.Method;

public record ProxyDataSourceInterceptor(DataSource dataSource) implements MethodInterceptor {

    public ProxyDataSourceInterceptor(final DataSource dataSource) {
        this.dataSource = ProxyDataSourceBuilder.create(dataSource).multiline().logQueryBySlf4j(SLF4JLogLevel.DEBUG).build();
    }

    public ProxyDataSourceInterceptor setDataSourceName(String dataSourceName) {
        if (this.dataSource instanceof ProxyDataSource proxyDataSource) {
            proxyDataSource.setDataSourceName(dataSourceName);
        }

        return this;
    }

    @Override
    public Object invoke(final MethodInvocation invocation) throws Throwable {
        final Method proxyMethod = ReflectionUtils.findMethod(this.dataSource.getClass(), invocation.getMethod().getName());
        if (proxyMethod != null) {
            return proxyMethod.invoke(this.dataSource, invocation.getArguments());
        }
        return invocation.proceed();
    }
}
